<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  
  <title>Java多线程 | conor_hua</title>
  <meta name="description" content="辉夜大小姐想让我写博客。" />
  <meta name="keywords" content="Java,Sakura,spring" />
  
    <link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/favicon00.ico">
  
  <meta http-equiv="x-dns-prefetch-control" content="on">
  <!--自定义看板娘-->
  <script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
  <script src="/live2d-widget/autoload.js"></script>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome/css/font-awesome.min.css"/>

  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/googlefont.css" media="all">
<!--  <link rel="dns-prefetch" href="//cdn.jsdelivr.net">-->
  <link rel="stylesheet" id="saukra_css-css" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/style.css" type="text/css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/lib.min.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/font.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/insight.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/jquery.fancybox.min.css" media="all">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/zoom.css" media="all">
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/sharejs.css">
  <link rel="stylesheet" href="/css/tags.css" media="all">
  <!--   <link rel="stylesheet" id="saukra_css-css" href="https://2heng.xin/wp-content/cache/autoptimize/css/autoptimize_ad42a61f4c7d4bdd9f91afcff6b5dda5.css
" type="text/css" media="all"> -->
  <script>
  /*Initial Variables*/
  var mashiro_option = new Object();
  var mashiro_global = new Object();
  mashiro_option.NProgressON = true;
  /* 
   * 邮箱信息之类的东西可以填在这里，这些js变量基本都作用于sakura-app.js
   * 这样的设置仅是为了方便在基于PHP开发的主题中设置js变量，既然移植到了Node上，我想或许可以精简这一逻辑吧
   */
  mashiro_option.email_domain = "";
  mashiro_option.email_name = "";
  mashiro_option.cookie_version_control = "";
  mashiro_option.qzone_autocomplete = false;
  mashiro_option.site_name = "Conor_hua";
  mashiro_option.author_name = "";
  mashiro_option.site_url = "https://conor_hua.gitee.io";
  mashiro_option.v_appId = "GyC3NzMvd0hT9Yyd2hYIC0MN-gzGzoHsz";
  mashiro_option.v_appKey = "mgOpfzbkHYqU92CV4IDlAUHQ";
  mashiro_option.mathjax = "0";
  mashiro_option.qq_api_url = "https://api.mashiro.top/qqinfo/"; 
  mashiro_option.qq_avatar_api_url = "https://api.mashiro.top/qqinfo/";

  // mashiro_option.jsdelivr_css_src = "https://cdn.jsdelivr.net/gh/moezx/cdn@3.4.5/css/lib.min.css";
  // mashiro_option.float_player_on = true;

  /*End of Initial Variables*/
  </script>
  <script type="text/javascript">
  var bg = "https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/6f005cbc1865ff1b706aba57347988ab.webp,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/ox83gp.jpg,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/a5fa4f9db760f58fc48f03d66b4967f7.webp,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/zm3vey.jpg,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/b3e8dae89b950b940dc0edd1e8cc0566.webp,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/j58y6y.jpg,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/4217z9.jpg,https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/j5zg2p.jpg".split(",");
  var bgindex = Math.floor(Math.random()*bg.length);
  if (!!window.ActiveXObject || "ActiveXObject" in window) { //is IE?
    alert('朋友，IE浏览器未适配哦~');
  }
  </script>
  <style type="text/css">
  .hljs-ln{border-collapse:collapse}.hljs-ln td{padding:0}.hljs-ln-n:before{content:attr(data-line-number)}
  </style>
  <style type="text/css">.site-top .lower nav{display:block !important;}.author-profile i,.post-like a,.post-share .show-share,.sub-text,.we-info a,span.sitename,.post-more i:hover,#pagination a:hover,.post-content a:hover,.float-content i:hover{color:#FE9600}.feature i,.download,.navigator i:hover,.links ul li:before,.ar-time i,span.ar-circle,.object,.comment .comment-reply-link,.siren-checkbox-radio:checked + .siren-checkbox-radioInput:after{background:#FE9600}::-webkit-scrollbar-thumb{background:#FE9600}.download,.navigator i:hover,.link-title,.links ul li:hover,#pagination a:hover,.comment-respond input[type='submit']:hover{border-color:#FE9600}.entry-content a:hover,.site-info a:hover,.comment h4 a,#comments-navi a.prev,#comments-navi a.next,.comment h4 a:hover,.site-top ul li a:hover,.entry-title a:hover,#archives-temp h3,span.page-numbers.current,.sorry li a:hover,.site-title a:hover,i.iconfont.js-toggle-search.iconsearch:hover,.comment-respond input[type='submit']:hover{color:#FE9600}.comments .comments-main{display:block !important;}.comments .comments-hidden{display:none !important;}background-position:center center;background-attachment:inherit;}
  </style>
<script src="https://cdn.jsdelivr.net/gh/conorhua/asset/js/hititle.js"></script>
<meta name="generator" content="Hexo 4.2.1"></head>

<body class="page-template page-template-user page-template-page-analytics page-template-userpage-analytics-php page page-id-1297 chinese-font serif isWebKit">
  <div class="scrollbar" id="bar">
  </div>
  <a href="#" class="cd-top faa-float animated"></a>
  <section id="main-container">
    <div class="headertop filter-dot">
  <div id="banner_wave_1"></div>
  <div id="banner_wave_2"></div>
  <figure id="centerbg" class="centerbg">
    <div class="focusinfo no-select">
      <div class="header-tou">
        <a href="https://conor_hua.gitee.io" target="_blank" rel="noopener">
          <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/xiaomai.jpg">
        </a>
      </div>
      <div class="header-info">
        <p id="jinrishici-sentence">正在加载今日诗词....</p>
        <script src="https://sdk.jinrishici.com/v2/browser/jinrishici.js" charset="utf-8"></script>
        <div class="top-social_v2">
          <li id="bg-pre">
            <img class="flipx" src="https://cdn.jsdelivr.net/gh/honjun/cdn@1.6/img/other/next-b.svg">
          </li>
          
          
          
          <li>
            <a href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=1_bi5eLm4_Tj4uGXpqb5tLi6" target="_blank" class="social-github" title="email">
              <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/email.png">
            </a>
          </li>
          
          
          
          <li class="wechat">
            <a href="/#">
              <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/wechat.png">
            </a>
            <div class="wechatInner">
              <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/1.jpg">
            </div>
          </li>
          
          
          
          <li id="bg-next">
            <img src="https://cdn.jsdelivr.net/gh/honjun/cdn@1.6/img/other/next-b.svg">
          </li>
        </div>
      </div>
    </div>
  </figure>
  
  <div id="video-container" style="display: none;">
    <video style="object-fit: fill" id="bgvideo" class="video" video-name="" src="" width="auto" preload="auto">
    </video>
    <div id="video-btn" class="loadvideo videolive">
    </div>
    <div id="video-add">
    </div>
    <div class="video-stu">
    </div>
  </div>
  
  <div class="headertop-down faa-float animated" onclick="headertop_down()">
    <span>
      <i class="fa fa-chevron-down" aria-hidden="true">
      </i>
    </span>
  </div>
</div>
    <div id="page" class="site wrapper">
      <header class="site-header no-select gizle sabit" role="banner">
 
  <div class="site-top">
    <div class="site-branding">
      <span class="site-title">
        <span class="logolink moe-mashiro">
          <a href="/">
            <span class="sakurasono">Conor_hua</span>
            <span class="shironeko"></span>
          </a>
        </span>
      </span>
    </div>
    <div class="searchbox search-form-submit">
      <i class="iconfont js-toggle-search iconsearch icon-search">
      </i>
    </div>
    <div id="show-nav" class="showNav mobile-fit">
      <div class="line line1">
      </div>
      <div class="line line2">
      </div>
      <div class="line line3">
      </div>
    </div>
    <div class="lower-cantiner">
      <div class="lower">
        <nav class="mobile-fit-control hide">
          <ul id="menu-new" class="menu">
            
              <li>
                <a href="/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-fort-awesome faa-shake" aria-hidden="true"></i>
                    首页
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="/archives">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-archive faa-shake" aria-hidden="true"></i>
                    归档
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/categories/%E6%8A%80%E6%9C%AF/">
                          <i class="fa fa-code" aria-hidden="true"></i>
                          技术
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/%E5%B9%B2%E8%B4%A7/">
                          <i class="fa fa-plug" aria-hidden="true"></i>
                          干货
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="javascript:;">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-list-ul faa-vertical" aria-hidden="true"></i>
                    清单
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/bangumis/">
                          <i class="fa fa-film faa-vertical" aria-hidden="true"></i>
                          番剧
                        </a>
                      </li>
                    
                      <li>
                        <a href="/categories/%E6%94%B6%E8%97%8F/">
                          <i class="fa fa-star" aria-hidden="true"></i>
                          收藏
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/tags/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-tags" aria-hidden="true"></i>
                    标签
                  </span>
                </a>
                
              </li>
            
              <li>
                <a href="javascript:;">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-leaf faa-wrench" aria-hidden="true"></i>
                    关于
                  </span>
                </a>
                
                  <ul class="sub-menu">
                    
                      <li>
                        <a href="/about/">
                          <i class="fa fa-meetup" aria-hidden="true"></i>
                          我？
                        </a>
                      </li>
                    
                      <li>
                        <a href="/theme-sakura/">
                          <i class="fa iconfont icon-sakura" aria-hidden="true"></i>
                          主题
                        </a>
                      </li>
                    
                  </ul>
                
              </li>
            
              <li>
                <a href="/links/">
                  <span class="faa-parent animated-hover">
                    <i class="fa  fa-link faa-shake" aria-hidden="true"></i>
                    友人帐
                  </span>
                </a>
                
              </li>
            
          </ul>
        </nav>
      </div>
    </div>
  </div>
</header>

      <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/sharejs.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.6/css/tocbot.css">
<div class="pattern-center-blank"></div>

  <div class="pattern-center single-center">
    <!-- 有配图默认渲染第一张 -->
    <div class="pattern-attachment-img">
        <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/upload.gif" data-src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/wallhaven-p86dyp.jpg" class="lazyload" onerror="imgError(this,3)" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;">
      </div>
    <header class="pattern-header single-header">
      <h1 class="entry-title">
      Java多线程</h1>
      <p class="entry-census">
        <span>
          <a href="">
            <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/xiaomai.jpg">
          </a>
        </span>
        <span>
          <a href="">Conor_hua</a>
        </span>
        <span class="bull">
        ·</span>
        2021-2-25
        
      
        ·<span id="readcount"></span>次阅读
      
      </p>
    </header>
  </div>

<div id="content" class="site-content">
  <div id="primary" class="content-area">
    <main id="main" class="site-main" role="main">
      <article id="post-1" class="post-1 post type-post status-publish format-standard has-post-thumbnail hentry category-uncategorized">
        <div class="toc"></div>
        <!--<div class="toc-entry-content"> <!-- 套嵌目录使用（主要为了支援评论）-->
        
        <div class="entry-content">
          <p>本博客是多线程学习的笔记。主要是记录方便日后回档。</p>
<p>本文参考视频如下：</p>
<p><a href="https://www.oracle.com/cn/java/technologies/java-se-api-doc.html" target="_blank" rel="noopener">api文档</a></p>
<p><a href="https://www.liaoxuefeng.com/wiki/1252599548343744/1306580742045730" target="_blank" rel="noopener">线程状态</a></p>
<p><a href="https://www.liaoxuefeng.com/wiki/1252599548343744/1306580911915042" target="_blank" rel="noopener">线程协作</a></p>
<h2 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h2><ul>
<li><strong>程序</strong> ：指令和数据的有序集合，是一个静态的概念。</li>
<li><strong>进程</strong> ：程序的一次执行过程，是动态的概念，是系统资源分配的单位。</li>
<li><strong>线程</strong> ：一个进程至少有一个线程，通常包含多个线程，是CPU调度和执行的单位。线程的运行是由操作系统来调度的，无法干预。</li>
</ul>
<h2 id="线程实现"><a href="#线程实现" class="headerlink" title="线程实现"></a>线程实现</h2><p>线程的三种创建方式</p>
<p><img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/blog/thread/way.png" alt="way"></p>
<p>thread是java.lang包下的类，继承了object对象，实现了Runnable接口.</p>
<p><img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/blog/thread/api_thread.png" alt="api_thread"></p>
<p>创建新执行线程通常有两种方法。一种方法是将类声明为 <code>Thread</code> 的子类。该子类应重写 <code>Thread</code> 类的  <code>run</code> 方法。接下来可以分配并启动该子类的实例。</p>
<pre><code class="java"> class PrimeThread extends Thread {
         long minPrime;
         PrimeThread(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }</code></pre>
<p>启动线程</p>
<pre><code class="java">  PrimeThread p = new PrimeThread(143);
     p.start();
</code></pre>
<p>方式一：继承Thread类，重写run（）方法，调用start（）启动线程</p>
<hr>
<p>创建线程的另一种方法是声明实现 <code>Runnable</code> 接口的类。该类然后实现 <code>run</code>  方法。然后可以分配该类的实例，在创建 <code>Thread</code> 时作为一个参数来传递并启动。</p>
<pre><code class="java">class PrimeRun implements Runnable {
         long minPrime;
         PrimeRun(long minPrime) {
             this.minPrime = minPrime;
         }

         public void run() {
             // compute primes larger than minPrime
              . . .
         }
     }</code></pre>
<p>启动线程</p>
<pre><code class="java">PrimeRun p = new PrimeRun(143);
     new Thread(p).start();</code></pre>
<p>方式二：实现Runnable接口，实现run（）方法，通过Thread对象调用start（）启动线程（静态代理）。推荐使用方式二创建线程，可以避免单继承的局限性。</p>
<hr>
<p>每个线程都有一个标识名，多个线程可以同名。如果线程创建时没有指定标识名，就会为其生成一个新名称。</p>
<hr>
<p>第三种方式：实现callable接口，实现call（）方法，创建执行服务，提交执行，获取结果，关闭服务。</p>
<p><code>Callable</code> 接口类似于Runnable，两者都是为那些其实例可能被另一个线程执行的类设计的。但是  <code>Runnable</code> 不会返回结果，并且无法抛出经过检查的异常。 </p>
<p>Callable的优点：可以定义返回值，可以抛出异常。</p>
<h2 id="线程状态"><a href="#线程状态" class="headerlink" title="线程状态"></a>线程状态</h2><p>Java线程的状态有以下几种：</p>
<ul>
<li><p>（初始）New：新创建的线程，尚未执行；</p>
</li>
<li><p>（运行）Runnable：运行中的线程，正在执行<code>run()</code>方法的Java代码；</p>
</li>
<li><p>（阻塞）Blocked：运行中的线程，因为某些操作被阻塞而挂起；</p>
</li>
<li><p>（等待）Waiting：运行中的线程，因为某些操作在等待中；</p>
</li>
</ul>
<ul>
<li>（超时等待）Timed Waiting：运行中的线程，因为执行<code>sleep()</code>方法正在计时等待；</li>
<li>（终止）Terminated：线程已终止，因为<code>run()</code>方法执行完毕。</li>
</ul>
<p><img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/blog/thread/state.png" alt="state"></p>
<p>当线程启动后，它可以在<code>Runnable</code>、<code>Blocked</code>、<code>Waiting</code>和<code>Timed Waiting</code>这几个状态之间切换，直到最后变成<code>Terminated</code>状态，线程终止。</p>
<p>线程终止的原因有：</p>
<ul>
<li>线程正常终止：<code>run()</code>方法执行到<code>return</code>语句返回；</li>
<li>线程意外终止：<code>run()</code>方法因为未捕获的异常导致线程终止；</li>
<li>对某个线程的<code>Thread</code>实例调用<code>stop()</code>方法强制终止（强烈不推荐使用）。</li>
</ul>
<h3 id="线程中断"><a href="#线程中断" class="headerlink" title="线程中断"></a>线程中断</h3><ul>
<li>设置标志位</li>
<li>使用interrupt()方法</li>
<li>（强烈不推荐）使用stop(),destroy()等过时方法 或者JDK不建议的方法</li>
</ul>
<h3 id="sleep"><a href="#sleep" class="headerlink" title="sleep"></a>sleep</h3><ul>
<li>sleep() 指定当前线程阻塞的毫秒数</li>
<li>sleep() 存在异常InterruptedException</li>
<li>sleep() 使当前线程进入TIMED_WAITING状态</li>
<li>sleep() 可以模拟网络延时，倒计时等</li>
<li>sleep() 不会释放对象锁</li>
</ul>
<h3 id="yield"><a href="#yield" class="headerlink" title="yield"></a>yield</h3><ul>
<li>暂停当前正在执行的线程对象，并执行其他线程。在多线程的情况下，由CPU决定执行哪一个线程，而yield()方法就是暂停当前的线程，让给其他线程（包括它自己）执行，具体由谁执行由CPU决定。</li>
<li>yield仅仅是给出建议，不一定成功，取决于cpu调度哪个线程</li>
</ul>
<h3 id="join"><a href="#join" class="headerlink" title="join"></a>join</h3><ul>
<li><p>通过对另一个线程对象调用<code>join()</code>方法可以等待其执行结束；</p>
</li>
<li><p>可以指定等待时间，超过等待时间线程仍然没有结束就不再等待；</p>
</li>
<li><p>对已经运行结束的线程调用<code>join()</code>方法会立刻返回。</p>
</li>
</ul>
<h3 id="线程优先级"><a href="#线程优先级" class="headerlink" title="线程优先级"></a>线程优先级</h3><ul>
<li><p>优先级可以用从1到10的范围指定。10表示最高优先级，1表示最低优先级，5是普通优先级</p>
</li>
<li><p>线程的优先级没有指定时，所有线程都携带普通优先级</p>
</li>
<li><p>通常情况下，高优先级的线程将会比低优先级的线程有<strong>更高的几率</strong>得到执行。</p>
</li>
<li><p>setPriority()设置优先级，getPriority()获取优先级</p>
</li>
<li><p><strong>Java程序中对线程所设置的优先级只是给操作系统一个建议，操作系统不一定会采纳。而真正的调用顺序，是由操作系统的线程调度算法决定的</strong>。</p>
</li>
</ul>
<h3 id="守护线程-daemon"><a href="#守护线程-daemon" class="headerlink" title="守护线程 - daemon"></a>守护线程 - daemon</h3><ul>
<li>java线程分为用户线程和守护线程</li>
<li>jvm必须确保用户线程执行完毕，但不用等待守护线程执行完毕</li>
<li>守护线程。如后台记录操作日志，监控内存，gc等。</li>
<li>通过thread.setDaemon（true） 设置守护线程</li>
</ul>
<h2 id="线程同步"><a href="#线程同步" class="headerlink" title="线程同步"></a>线程同步</h2><ul>
<li><p>线程同步其实是一种等待机制，多个同时访问同一资源的线程进入这个资源的等待池形成队列，等待前面线程使用完毕再轮到下一个线程使用。</p>
</li>
<li><p>线程同步为了解决线程安全问题。</p>
</li>
<li><p>StringBuffer是线程安全的，HashTable是线程安全的。<code>String</code>，<code>Integer</code>，<code>LocalDate</code>等不变类它们的所有成员变量都是<code>final</code>，多线程同时访问时只能读不能写，这些不变类也是线程安全的。</p>
</li>
<li><p>一个类没有特殊说明，默认不是thread-safe</p>
</li>
<li><p>通过合理的设计和数据封装可以让一个类变为“线程安全”；</p>
</li>
</ul>
<h3 id="锁-synchronized"><a href="#锁-synchronized" class="headerlink" title="锁-synchronized"></a>锁-synchronized</h3><ul>
<li>锁机制能带来线程安全</li>
<li>一个线程持有锁会导致其他所有需要此锁的线程挂起</li>
<li>加锁，释放锁会导致较多的上下文切换和调度延时，引起性能问题</li>
<li>如果一个优先级高的线程等待一个优先级低的线程释放锁，会导致优先倒置，引起性能问题</li>
<li>用<code>synchronized</code>修饰方法可以把整个方法变为同步代码块，<code>synchronized</code>方法加锁对象是<code>this</code></li>
</ul>
<p>使用<code>synchronized</code>：</p>
<ol>
<li>找出修改共享变量的线程代码块；</li>
<li>选择一个共享实例作为锁；</li>
<li>使用<code>synchronized(lockObject) { ... }</code></li>
</ol>
<p>不需要synchronized的操作</p>
<p>JVM规范定义了几种原子操作：</p>
<ul>
<li>基本类型（<code>long</code>和<code>double</code>除外）赋值，例如：<code>int n = m</code>；</li>
<li>引用类型赋值，例如：<code>List&lt;String&gt; list = anotherList</code>。</li>
</ul>
<p><code>long</code>和<code>double</code>是64位数据，JVM没有明确规定64位赋值操作是不是一个原子操作，不过在x64平台的JVM是把<code>long</code>和<code>double</code>的赋值作为原子操作实现的。</p>
<h3 id="死锁"><a href="#死锁" class="headerlink" title="死锁"></a>死锁</h3><p>​        多个线程各自占有一些共享资源，并且相互等待其他线程占有的资源才能运行，而导致两个或者多个线程都在等待对方释放资源，都停止执行的情形。某一个同步块同时拥有两个以上的对象锁时，就有可能发生死锁的情况。</p>
<p>死锁的必要条件：</p>
<ul>
<li><p>互斥条件：一个资源每次只能被一个线程使用</p>
</li>
<li><p>请求与保持条件：一个线程因请求资源而阻塞时，对已获得的资源保持不放</p>
</li>
<li><p>不剥夺条件：线程已获得的资源，在未使用完之前，不能强行剥夺</p>
</li>
<li><p>循环等待条件：若干线程之间形成一种头尾相接的循环等待资源关系</p>
</li>
</ul>
<p>破坏其中一个条件即可避免死锁的产生。</p>
<h3 id="Lock锁"><a href="#Lock锁" class="headerlink" title="Lock锁"></a>Lock锁</h3><p>从Java 5开始，引入了一个高级的处理并发的<code>java.util.concurrent</code>包，它提供了大量更高级的并发功能，能大大简化多线程程序的编写。</p>
<p>我们知道Java语言直接提供了<code>synchronized</code>关键字用于加锁，但这种锁一是很重，二是获取时必须一直等待，没有额外的尝试机制。</p>
<p><code>java.util.concurrent.locks</code>包提供的<code>ReentrantLock</code>用于替代<code>synchronized</code>加锁，我们来看一下传统的<code>synchronized</code>代码：</p>
<p>synchronized 与 Lock 的区别</p>
<ul>
<li>Lock是显示锁（手动开启和关闭锁） synchronized是隐式锁（出了作用域自动释放锁）</li>
<li>Lock只有代码块锁，synchronized有代码块锁和方法锁</li>
<li>使用Lock锁，JVM花费的时间更少，性能更好。</li>
</ul>
<h2 id="线程协作"><a href="#线程协作" class="headerlink" title="线程协作"></a>线程协作</h2><p><code>wait</code>和<code>notify</code>用于多线程协调运行：</p>
<ul>
<li>在<code>synchronized</code>内部可以调用<code>wait()</code>使线程进入等待状态；</li>
<li>必须在已获得的锁对象上调用<code>wait()</code>方法；</li>
<li>在<code>synchronized</code>内部可以调用<code>notify()</code>或<code>notifyAll()</code>唤醒其他等待线程；</li>
<li>必须在已获得的锁对象上调用<code>notify()</code>或<code>notifyAll()</code>方法；</li>
<li>已唤醒的线程还需要重新获得锁后才能继续执行。</li>
</ul>
<h2 id="线程池"><a href="#线程池" class="headerlink" title="线程池"></a>线程池</h2><p>​        经常创建和销毁线程对性能产生影响。</p>
<p>​        提前创建好多个线程，放入线程池，使用时可以直接拿取，使用完放回线程池中。可以避免频繁创建和销毁，实现重复利用，提供性能。</p>
<p>好处：</p>
<ul>
<li><p>提高响应速度</p>
</li>
<li><p>减低资源消耗</p>
</li>
<li><p>便于线程管理</p>
</li>
</ul>

        </div>
        <!-- .entry-content -->
        
        <p></p>
          
        <div style="text-align:center; width: 100%" class="social-share share-mobile" data-disabled="diandian, tencent"></div>
        <footer class="post-footer">
          <div class="post-lincenses"><a href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh" target="_blank" rel="nofollow"><i class="fa fa-creative-commons" aria-hidden="true"></i> 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议</a></div>
          <div class="post-tags">
            <div class="tag-cloud">
              <div class="tag-cloud-title">
              </div>
              <div class="tag-cloud-tags">
              <a href="/tags/CDN/" style="font-size: 10px; color: #f38181">CDN</a> <a href="/tags/Chrome/" style="font-size: 10px; color: #f38181">Chrome</a> <a href="/tags/Collection/" style="font-size: 10px; color: #f38181">Collection</a> <a href="/tags/ElasticSearch/" style="font-size: 10px; color: #f38181">ElasticSearch</a> <a href="/tags/IO%E6%B5%81/" style="font-size: 10px; color: #f38181">IO流</a> <a href="/tags/JVM/" style="font-size: 10px; color: #f38181">JVM</a> <a href="/tags/Java/" style="font-size: 16.67px; color: #b4c1b8">Java</a> <a href="/tags/Linux/" style="font-size: 10px; color: #f38181">Linux</a> <a href="/tags/MySQL/" style="font-size: 10px; color: #f38181">MySQL</a> <a href="/tags/OIS/" style="font-size: 10px; color: #f38181">OIS</a> <a href="/tags/Redis/" style="font-size: 13.33px; color: #d4a19c">Redis</a> <a href="/tags/SQL/" style="font-size: 10px; color: #f38181">SQL</a> <a href="/tags/Springboot/" style="font-size: 10px; color: #f38181">Springboot</a> <a href="/tags/TCP-IP/" style="font-size: 10px; color: #f38181">TCP/IP</a> <a href="/tags/Tomcat/" style="font-size: 10px; color: #f38181">Tomcat</a> <a href="/tags/aop/" style="font-size: 10px; color: #f38181">aop</a> <a href="/tags/bili/" style="font-size: 10px; color: #f38181">bili</a> <a href="/tags/eclipse/" style="font-size: 10px; color: #f38181">eclipse</a> <a href="/tags/git/" style="font-size: 10px; color: #f38181">git</a> <a href="/tags/github/" style="font-size: 13.33px; color: #d4a19c">github</a> <a href="/tags/ioc/" style="font-size: 10px; color: #f38181">ioc</a> <a href="/tags/java/" style="font-size: 20px; color: #95e1d3">java</a> <a href="/tags/jsdelivr/" style="font-size: 10px; color: #f38181">jsdelivr</a> <a href="/tags/oracle/" style="font-size: 10px; color: #f38181">oracle</a> <a href="/tags/spring/" style="font-size: 13.33px; color: #d4a19c">spring</a> <a href="/tags/sring/" style="font-size: 10px; color: #f38181">sring</a> <a href="/tags/vscode/" style="font-size: 10px; color: #f38181">vscode</a> <a href="/tags/web/" style="font-size: 10px; color: #f38181">web</a> <a href="/tags/%E5%8F%8D%E5%B0%84/" style="font-size: 10px; color: #f38181">反射</a> <a href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" style="font-size: 10px; color: #f38181">多线程</a> <a href="/tags/%E5%AE%9E%E4%B9%A0/" style="font-size: 10px; color: #f38181">实习</a> <a href="/tags/%E6%8E%92%E5%BA%8F/" style="font-size: 10px; color: #f38181">排序</a> <a href="/tags/%E6%B3%A8%E8%A7%A3/" style="font-size: 10px; color: #f38181">注解</a> <a href="/tags/%E6%B4%BE%E5%A4%A7%E6%98%9F/" style="font-size: 10px; color: #f38181">派大星</a> <a href="/tags/%E7%BD%91%E7%BB%9C/" style="font-size: 10px; color: #f38181">网络</a>
              </div>
            </div>
          </div>
          <div class="post-share">
            <div class="social-share sharehidden share-component"></div>
            <i class="iconfont show-share icon-forward"></i>
          </div>
        </footer><!-- .entry-footer -->
      </article>
      <!-- #post-## -->
      <div class="toc" style="background: none;"></div>
      <section class="post-squares nextprev">
        
          
            <div class="post-nepre half previous">
          
            <a href="/posts/c51233f6.html" rel="prev">
              <div class="background">
<!--                <img class="lazyload" src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/upload.gif" data-src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/wallhaven-m9wv21.png" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;" onerror="imgError(this,3)" src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/wallhaven-m9wv21.png">-->
                
                <img class="lazyload" src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/upload.gif" data-src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/wallhaven-m9wv21.png" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;" onerror="imgError(this,3)" >
              </div>
              <span class="label">
              Previous Post</span>
              <div class="info">
                <h3>
                JavaIO流</h3>
                <hr>
              </div>
            </a>
          </div>
        
        
          
            <div class="post-nepre half next">
          
            <a href="/posts/93a8c831.html" rel="next">
              <div class="background">
                
                <img class="lazyload" src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/upload.gif" data-src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/banner/wallhaven-mdjolk.jpg" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;" onerror="imgError(this,3)" >
              </div>
              <span class="label">
              Next Post</span>
              <div class="info">
                <h3>
                Oracle12c创建用户</h3>
                <hr>
              </div>
            </a>
          </div>
        
      </section>
      
      <section class="author-profile">
        <div class="info" itemprop="author" itemscope="" itemtype="https://schema.org/Person">
          <a href="" class="profile gravatar"><img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/xiaomai.jpg" itemprop="image" alt="Conor_hua" height="70" width="70"></a>
          <div class="meta">
            <span class="title">Author</span>
            <h3 itemprop="name">
            <a href="" itemprop="url" rel="author">Conor_hua</a>
            </h3>
          </div>
        </div>
        <hr>
        <p><i class="iconfont icon-write"></i></p>
      </section>
    </main><!-- #main -->
  </div><!-- #primary -->
</div>


    </div>    
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="请输入关键词..."/>
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            // PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
    <!-- <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2021 Conor_hua<br>
      powered_by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer> -->
<footer id="colophon" class="site-footer" role="contentinfo">
    <div class="site-info">
        <div class="footertext">
            <div class="img-preload">
                <img src="https://cdn.jsdelivr.net/gh/honjun/cdn@1.6/img/other/wordpress-rotating-ball-o.svg">
                <img src="https://cdn.jsdelivr.net/gh/honjun/cdn@1.6/img/other/disqus-preloader.svg">
            </div>
            
            <p>本站总访问量：<a id="allcount"></a></p>
            <p style="color: #666666;">it you can dream it you can do it</p>
            
                <p id="momk" style="font-family: 'Ubuntu', sans-serif;color: #b9b9b9;"></p>
            
        </div>
        <div class="footer-device">
            <p style="font-family: 'Ubuntu', sans-serif;">
 <span style=""> <a 
                         style="color: 	#FF69B4;;text-decoration: underline dotted rgba(0, 0, 0, .1);">Conor_hua</a> <i
             class="iconfont icon-sakura rotating" style="color: #ffc0cb;display:inline-block"></i> Theme <a
             href="https://github.com/xbclub/Hexo-theme-sakura" target="_blank"
             style="color: #FF69B4;;text-decoration: underline dotted rgba(0, 0, 0, .1);">Sakura</a><a
             
             style="color: #b9b9b9;;text-decoration: underline dotted rgba(0, 0, 0, .1);">, Powered by</a><a
             href="https://github.com/hexojs/hexo" target="_blank"
             style="color: #FF69B4;;text-decoration: underline dotted rgba(0, 0, 0, .1);"> Hexo</a>
        </span>
            </p>
        </div>
    </div><!-- .site-info -->
    <!--壁纸切换-->
  <div class="skin-menu no-select" id="mainskin"  style="position: fixed">
    <div class="theme-controls row-container">
        <ul class="menu-list">
            <li id="white-bg"> <i class="fa fa-television" aria-hidden="true"></i></li>
            <li id="sakura-bg"> <i class="iconfont icon-sakura"></i></li>
            <li id="gribs-bg"> <i class="fa fa-slack" aria-hidden="true"></i></li>
            <li id="KAdots-bg"> <i class="iconfont icon-dots"></i></li>
            <li id="totem-bg"> <i class="fa fa-optin-monster" aria-hidden="true"></i></li>
            <li id="pixiv-bg"> <i class="iconfont icon-pixiv"></i></li>
            <li id="bing-bg"> <i class="iconfont icon-bing"></i></li>
            <li id="dark-bg"> <i class="fa fa-moon-o" aria-hidden="true"></i></li>
        </ul>
    </div>
    <div class="font-family-controls row-container">
        <button type="button" class="control-btn-serif selected" data-mode="serif" onclick="mashiro_global.font_control.change_font()">Serif</button>
        <button type="button" class="control-btn-sans-serif" data-mode="sans-serif" onclick="mashiro_global.font_control.change_font()">Sans Serif</button>
    </div>
</div>   
<canvas id="night-mode-cover"></canvas> 
  <div class="changeSkin-gear no-select">
    <div class="keys" id="setbtn"> <span id="open-skinMenu"> 切换壁纸 | SCHEME TOOL 
      &nbsp;<i class="iconfont icon-gear inline-block rotating"></i> </span></div>
</div><!--skin.end-->
</footer>


<!--<script src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.7/js/tocbot.min.js"></script>-->

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/lib.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/InsightSearch.js"></script>
<script type="text/javascript"
        src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/jquery.fancybox.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/zoom.min.js"></script>

<script type="text/javascript" src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@1.2/js/sakura-app.js"></script>
    
<script src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/Valine.min.js'></script>
<script src="https://cdn.jsdelivr.net/gh/xbclub/staticCDN@0.8/js/botui.js"></script>
<!-- 不蒜子 网页计数器 -->

      
       <script>
  fetch('https://counts.42cloud.cn/api/counts.html')
        .then(response => response.json())
        .then(data => {
              if (document.getElementById("readcount")) {
                document.getElementById("readcount").innerHTML=data.Count;
            }
            if (document.getElementById("allcount")){
                document.getElementById("allcount").innerHTML=data.Allcount;
            }
        })
        .catch(err => console.error(err))
</script>
      
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.4.2/tocbot.min.js"></script> -->
<script type="text/javascript">
    /* <![CDATA[ */
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
        var Poi = {
            "pjax": "1",
            "movies": {"url": "https://cdn.jsdelivr.net/gh/honjun/hojun@1.2", "name": "Unbroken.mp4", "live": "close"},
            "windowheight": "fixed",
            "codelamp": "close",
            "ajaxurl": "",
            "order": "asc",
            "formpostion": "bottom"
        };
    } else {
        var Poi = {
            "pjax": "1",
            "movies": {"url": "https://cdn.jsdelivr.net/gh/honjun/hojun@1.2", "name": "Unbroken.mp4", "live": "open"},
            "windowheight": "auto",
            "codelamp": "close",
            "ajaxurl": "",
            "order": "asc",
            "formpostion": "bottom"
        };
    }
    /* ]]> */

</script>
<script>
    $(document).ready(function () {
        if ($(".toc").length > 0 && document.body.clientWidth > 1200) {
            if ($(".pattern-center").length > 0) { //有图的情况
                tocbot.init({
                    // Where to render the table of contents.
                    tocSelector: '.toc', // 放置目录的容器
                    // Where to grab the headings to build the table of contents.
                    contentSelector: '.entry-content', // 正文内容所在
                    // Which headings to grab inside of the contentSelector element.
                    scrollSmooth: true,
                    headingSelector: 'h1, h2, h3, h4, h5', // 需要索引的标题级别
                    headingsOffset: -400,
                    scrollSmoothOffset: -85
                });
            } else {
                tocbot.init({
                    // Where to render the table of contents.
                    tocSelector: '.toc', // 放置目录的容器
                    // Where to grab the headings to build the table of contents.
                    contentSelector: '.entry-content', // 正文内容所在
                    // Which headings to grab inside of the contentSelector element.
                    scrollSmooth: true,
                    headingSelector: 'h1, h2, h3, h4, h5', // 需要索引的标题级别
                    headingsOffset: -85,
                    scrollSmoothOffset: -85
                });
            }
            var offsetTop = $('.toc').offset().top - 95;
            window.onscroll = function () {
                var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
                if (scrollTop >= offsetTop) {
                    $('.toc').addClass('toc-fixed');
                } else {
                    $('.toc').removeClass('toc-fixed');
                }
            }
        }
    });

</script>
<span style="color: #FF69B4 ;padding-left: 20px;">
    <i class="fa fa-clock-o" aria-hidden="true"></i>
    <span id="time" align="center">载入时间中...</span>

    <script type="text/javascript">
        function NewDate(str) {
            str = str.split('-');
            var date = new Date();
            date.setUTCFullYear(str[0], str[1] - 1, str[2]);
            date.setUTCHours(0, 0, 0, 0);
            return date;
        }

        function momxc() {
            var birthDay = NewDate("2020-7-16");
            var today = new Date();
            var timeold = today.getTime() - birthDay.getTime();
            var sectimeold = timeold / 1000
            var secondsold = Math.floor(sectimeold);
            var msPerDay = 24 * 60 * 60 * 1000;
            var e_daysold = timeold / msPerDay;
            var daysold = Math.floor(e_daysold);
            var e_hrsold = (daysold - e_daysold) * -24;
            var hrsold = Math.floor(e_hrsold);
            var e_minsold = (hrsold - e_hrsold) * -60;
            var minsold = Math.floor((hrsold - e_hrsold) * -60);
            var seconds = Math.floor((minsold - e_minsold) * -60).toString();
            document.getElementById("momk").innerHTML = "本小破站已勉强维持生活" + daysold + "天" + hrsold + "小时" + minsold + "分" + seconds + "秒";
            setTimeout(momxc, 1000);
        }
        
        momxc();
    </script>


</span>


    <div class="openNav no-select" style="height: 50px;">
      <div class="iconflat no-select" style="width: 50px; height: 50px;">
        <div class="icon"></div>
      </div>
      <div class="site-branding search-form-submit">
        <i class="iconfont js-toggle-search iconsearch icon-search"></i>
      </div>
    </div>
  </section>
  <div id="mo-nav" class="">
  <div class="m-avatar">
    <img src="https://cdn.jsdelivr.net/gh/conorhua/asset/ima/xiaomai.jpg">
  </div>
  <p style="text-align: center; color: #333; font-weight: 900; font-family: 'Ubuntu', sans-serif; letter-spacing: 1.5px">Conor_hua</p>
  <p style="text-align: center; word-spacing: 20px;">
    
  </p>
  <ul id="menu-new-1" class="menu">
    
      <li>
        <a href="/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-fort-awesome faa-shake" aria-hidden="true"></i>
            首页
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="/archives">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-archive faa-shake" aria-hidden="true"></i>
            归档
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/categories/%E6%8A%80%E6%9C%AF/">
                  <i class="fa fa-code" aria-hidden="true"></i>
                  技术
                </a>
              </li>
            
              <li>
                <a href="/categories/%E5%B9%B2%E8%B4%A7/">
                  <i class="fa fa-plug" aria-hidden="true"></i>
                  干货
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="javascript:;">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-list-ul faa-vertical" aria-hidden="true"></i>
            清单
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/bangumis/">
                  <i class="fa fa-film faa-vertical" aria-hidden="true"></i>
                  番剧
                </a>
              </li>
            
              <li>
                <a href="/categories/%E6%94%B6%E8%97%8F/">
                  <i class="fa fa-star" aria-hidden="true"></i>
                  收藏
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/tags/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-tags" aria-hidden="true"></i>
            标签
          </span>
        </a>
        
      </li>
    
      <li>
        <a href="javascript:;">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-leaf faa-wrench" aria-hidden="true"></i>
            关于
          </span>
        </a>
        
          <ul class="sub-menu">
            
              <li>
                <a href="/about/">
                  <i class="fa fa-meetup" aria-hidden="true"></i>
                  我？
                </a>
              </li>
            
              <li>
                <a href="/theme-sakura/">
                  <i class="fa iconfont icon-sakura" aria-hidden="true"></i>
                  主题
                </a>
              </li>
            
          </ul>
        
      </li>
    
      <li>
        <a href="/links/">
          <span class="faa-parent animated-hover">
            <i class="fa  fa-link faa-shake" aria-hidden="true"></i>
            友人帐
          </span>
        </a>
        
      </li>
    
  </ul>
  <p style="text-align: center; font-size: 13px; color: #b9b9b9;">&copy 2019 hexo-sakura</p>
</div>
<button onclick="topFunction()" class="mobile-cd-top" id="moblieGoTop" title="Go to top" style="display: none;"><i class="fa fa-chevron-up" aria-hidden="true"></i></button>
  
</body>
<script src="https://cdn.jsdelivr.net/gh/conorhua/asset/js/noSomeKey.js"></script>
</html>